package com.yy.sso.authority.center.service.impl;

import com.alibaba.fastjson.JSON;
import com.yy.sso.authority.center.model.Permission;
import com.yy.sso.authority.center.model.Role;
import com.yy.sso.authority.center.model.User;
import com.yy.sso.authority.center.service.IPermissionService;
import com.yy.sso.authority.center.service.IRoleService;
import com.yy.sso.authority.center.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String userName){
        User user = this.userService.findUserByUserName(userName);
        if (user == null) {
            throw new UsernameNotFoundException("userName" + userName + "is not exists");
        }
        List<Role> roleList = this.roleService.listByUserId(user.getId());
        List<Permission> permissionList = this.permissionService.getPermissionsByUserId(user.getId());

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        // 角色权限需要加上 role_ 前缀加roleName,后面角色权限用hashRole，菜单权限用hasAuthority
        roleList.forEach(role -> grantedAuthorities.add(new SimpleGrantedAuthority("role_"+role.getEnname())));
        permissionList.forEach(permission -> grantedAuthorities.add(new SimpleGrantedAuthority(permission.getEnname())));
        //如果想放自定义用户信息，请使用以下，不过建议不要讲敏感信息丢在jwt里面
        //String principal = JSON.toJSONString(user);
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);

    }
}
